<?php


namespace Log4tp\Service;


/**
 * 用户生成log id 类
 */
class Logid
{
    //short traceId
    private static $_stid;

    //log seq
    private static $_seq;

    //log seq init
    private static $seqInit = false;

    // trace id
    private static $_tid;

    //get trace id
    public static function getTraceId()
    {
        if (self::$_tid != null) {
            return self::$_tid;
        }
        mt_srand();
        if (isset($_SERVER['HTTP_PHP_TID'])) {
            $tid = $_SERVER['HTTP_PHP_TID'];
        } else {
            $tid = round(microtime(1) * 1000) . "_" . self::randomkeys(4);
        }
        self::$_tid = $tid;
        return $tid;
    }

    public static function stid()
    {
        if (!empty(self::$_stid)) {
            return self::$_stid;
        }
        $str = self::getTraceId();
        $arr = explode("_", $str);
        $str = $arr[1];
        $int = $arr[0];
        for ($i = 0; $i < strlen($str); $i++) {
            if (\is_numeric($str[$i])) {
                $int += $str[$i];
            } else {
                $int += ord($str[$i]);
            }
        }
        $int         = (int)$int;
        self::$_stid = \base_convert($int, 10, 36);
        return self::$_stid;
    }

    //get seq
    public static function getNextSeq($pre = false)
    {
        if (empty(self::$_seq) && !empty($_SERVER['HTTP_PHP_SEQ'])) {
            self::$_seq = $_SERVER['HTTP_PHP_SEQ'];
        }

        if (self::$_seq == null) {
            if ($pre == true) {
                return "1.1";
            }
            self::$_seq    = "1.1";
            self::$seqInit = true;
            return self::$_seq;
        }

        //向下添加一层
        if (self::$seqInit === false) {
            $seq = self::$_seq;
            $seq .= ".1";
            if ($pre == true) {
                return $seq;
            }
            self::$_seq    = $seq;
            self::$seqInit = true;
            return self::$_seq;
        }

        $prefix = substr(self::$_seq, 0, strrpos(self::$_seq, "."));
        $num    = substr(self::$_seq, strrpos(self::$_seq, ".") + 1);
        $seq    = $prefix . "." . ((int)$num + 1);
        if ($pre == true) {
            return $seq;
        }
        self::$_seq = $seq;
        return self::$_seq;
    }

    //get now seq
    public static function getNowSeq()
    {
        return self::$_seq;
    }

    public static function  randomkeys( $length = 8 ) {
        // 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $password = '';
        for ( $i = 0; $i < $length; $i++ )
        {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
            $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }
        return $password;
    }
}